using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using WebApplication1.Auth;

namespace WebApplication1;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        
        builder.Services.AddHttpContextAccessor();
        // Add services to the container.

        builder.Services.AddControllers();
        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();
        
        var Jwtconfiguration = builder.Configuration.GetSection("JWT");
        
        builder.Services.AddSingleton(new JWTHelp(Jwtconfiguration));
        
        //jwt 注册服务
        builder.Services.AddAuthentication(option =>
        {
            //选择认证方案 JWT默认方案
            option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(option =>
        {
            option.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true, //是否验证Issuer
                ValidIssuer = Jwtconfiguration["Issuer"], //发行人
                ValidateAudience = true, //是否验证Audience
                ValidAudience = Jwtconfiguration["Audience"], //订阅人
                ValidateIssuerSigningKey = true, //是否验证签名
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Jwtconfiguration["SecretKey"])), //密钥
                ValidateLifetime = true, //是否验证Token有效期，这里使用绝对时间，所以不需要
                ClockSkew = TimeSpan.FromSeconds(30), //时间偏移量
                RequireExpirationTime = true, //是否要求Token中必须包含ExpirationTime
                //AudienceValidator = (Microsoft.IdentityModel.Tokens.AudienceValidator)null, //自定义Audience验证
            };
        });

        builder.Services.AddAuthorization(options =>
        {
             options.AddPolicy("Admin", policy => policy.RequireRole("r_admin"));
             options.AddPolicy("User", policy => policy.RequireRole("User"));
             options.AddPolicy("AdminRequireMentWds", o =>
             {
                
                var myAdminRequirement = new TestAdminRequirement(); // 可以传递参数
                myAdminRequirement.myName = "zhangsanfeng";
                o.Requirements.Add(myAdminRequirement); // 完全自定义
             });
        });


         builder.Services.AddSingleton<IAuthorizationHandler, TestMustRoleAdminHandle>();

        var app = builder.Build();
        
        

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();
        

        
        //调用中间件：UseAuthentication（认证），必须在所有需要身份认证的中间件前调用，比如 UseAuthorization（授权）。
        app.UseAuthentication();
        app.UseAuthorization();


        app.MapControllers();

        app.Run();
    }
}